/*
 * 版权所有：杭州领域向尚科技有限公司
 * 地址：浙江省杭州市滨江区滨安路688号天和高科技产业园5-2311
 *
 * (c) Copyright Hangzhou  Area Up Technology Co., Ltd.
 */

package org.elanfox.cloud.mybatis.base;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.ObjectUtils;
import org.elanfox.cloud.common.base.BasePO;
import org.elanfox.cloud.common.dto.BaseSearchDTO;
import org.elanfox.cloud.mybatis.common.Mapper;

import java.util.List;

/**
 * @author allan
 * @date 26/10/2017
 */
public abstract class AbstractCrudService<T extends BasePO, ID> implements CrudService<T, ID> {
    protected final Mapper<T, ID> mapper;

    @Override
    public T insert(T t) {
        mapper.insert(t);

        return t;
    }

    @Override
    public T save(T t) {
        if (ObjectUtils.isEmpty(t.getId())) {
            mapper.insert(t);
        } else {
            mapper.updateByPrimaryKey(t);
        }

        return t;
    }

    @Override
    public T save(T t, boolean isUpdate) {
        return isUpdate ? update(t) : insert(t);
    }

    @Override
    public T update(T t) {
        mapper.updateByPrimaryKey(t);

        return t;
    }

    @Override
    public List<T> findByIds(List<ID> idList) {
        return mapper.selectByIdList(idList);
    }

    @Override
    public List<T> findByIds(String ids) {
        return mapper.selectByIds(ids);
    }

    @Override
    public int deleteById(ID id) {
        return mapper.deleteByPrimaryKey(id);
    }

    @Override
    public int deleteByIds(List<ID> ids) {
        return deleteByIds(ids);
    }

    @Override
    public List<T> findAll(BaseSearchDTO searchDTO) {
        return mapper.selectByExample(example(searchDTO));
    }

    protected AbstractCrudService(Mapper<T, ID> mapper) {
        this.mapper = mapper;
    }

    @Override
    public T findById(ID id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public List<T> findAll() {
        return mapper.selectAll();
    }

    protected String likeAll(String field) {
        return "%" + field + "%";
    }

    protected String likeLeft(String field) {
        return "%" + field + "%";
    }

    protected String likeRight(String field) {
        return field + "%";
    }

    /**
     * 创建一个Specification
     *
     * @param searchDTO 查询条件
     * @return {@link Example}
     */
    protected abstract Example example(BaseSearchDTO searchDTO);

    @Override
    public PageInfo<T> findAll(int pageIndex, int pageSize, BaseSearchDTO searchDTO) {
        return PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(() -> findAll(searchDTO));
    }

    @Override
    public PageInfo<T> findAll(int pageIndex, int pageSize) {
        return PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(mapper::selectAll);
    }
}
